﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Yyyg.IBLL;
using Yyyg.Models;
using Yyyg.WebUI.Models;

namespace Yyyg.WebUI.Controllers
{

    [Authorize]
    public class UserInfoController : Controller
    {
        public IMemberService users { get; set; }

        public IOrdersService orders { get; set; }

        public LuckyEntities db { get; set; }

        // GET: UserInfo
        public ActionResult UserInfo()
        {
            var uid = HttpContext.GetUserID();
            var user = db.Member.First(s => s.Uid == uid);
            ViewBag.HeadUrl = Server.MapUserHead(user.Uid);
            return View(user);
        }

        public ActionResult PartialFavorites(int pindex)
        {
            var uid = HttpContext.GetUserID();
            int datalen;
            var favlimit = db.UserCollect.Where(w => w.Uid == uid).OrderByDescending(o => o.CreateTime).QueryPage(pindex, 8, out datalen).ToArray();
            ViewBag.UserCollectLen = datalen;
            return View("_PartialFavorites", favlimit);
        }

        //地址页
        public ActionResult Addr()
        {
            int uid = HttpContext.GetUserID();
            var ads = db.ReceInfo.Where(s => s.Uid == uid);
            return View(ads.ToList());
        }

        //我的云购页
        public ActionResult Myyg(int? tjx)
        {
            var uid = HttpContext.GetUserID();
            var user = users.GetUser(uid);
            //根据夺宝项进行分组,因为用户可能同一夺宝项购买多次
            var ors = db.Orders
                .Where(w => w.Uid == uid)
                .GroupBy(g => g.Rush_id)
                .ToArray();

            MyygVM vm = new MyygVM();
            vm.AllYgs = ors.Select(s =>
            {
                var or = s.First();//获取分组中的头项数据
                return new MyygVM.YgItem()
                {
                    ImgSrc = or.Rushby_all.Goods.GetMainImgPath(),
                    RushID = or.Rush_id,
                    OrderID = or.Id,
                    Rem = or.Rushby_all.Rem,
                    Join = s.Sum(m => m.Bycount),//计算该分组下所有的购买总数
                    Pernum = or.Rushby_all.Per_num,
                    Status = or.Rushby_all.Status,
                    Sum = or.Rushby_all.All_told,
                    Title = or.Rushby_all.Goods.Title,
                    CreateTime = or.Createtime
                };
            }).OrderByDescending(o => o.CreateTime).ToList();
            //查询用户尚未查看的开奖的商品ID
            var newlott = db.Rushby_over.
                Where(
                w => w.Createtime > user.LastMyygTime
                && db.Orders.Where(w1 => w1.Uid == uid).Select(s => s.Rush_id).Contains(w.Rush_id)
                ).Select(s => s.Rush_id).ToArray();

            ViewBag.NewLott = newlott;
            //是否直接定位到已开奖
            ViewBag.ToNewJx = tjx == 1;

            //更新用户上次访问云购的时间
            users.UpdateLastMyygTime(uid);
            return View(vm);
        }

        //支出详情页
        public ActionResult OrderDet()
        {
            return View();
        }

        //中奖记录
        public ActionResult MyWin()
        {
            var uid = HttpContext.GetUserID();
            ViewBag.DataNum = db.Rushby_over.Where(w => w.Uid == uid).Count();
            return View();
        }

        public ActionResult MyWinQueryPage(int pindex, int psize)
        {
            var uid = HttpContext.GetUserID();
            var list = db.Rushby_over.Where(w => w.Uid == uid).OrderByDescending(o => o.Createtime).QueryPage(pindex, psize).ToList();
            return View("_PartialNjxItems", list);
        }

        [OutputCache(Duration = 20, Location = System.Web.UI.OutputCacheLocation.Client)]
        //云购码详情弹出层
        public ActionResult RobDet(int rhid)
        {
            var uid = HttpContext.GetUserID();
            var ors = db.Orders.Where(w => w.Uid == uid && w.Rush_id == rhid).OrderBy(o => o.Id);
            var robs = new List<Tuple<int, int>>();
            var rush = db.Rushby_all.FirstOrDefault(f => f.Id == rhid);

            //查询所有夺宝号区间
            var areas = db.Rushby_det.Where(w => w.Rushid == rhid && w.Uid == uid)
            .ToArray()
            .Select(s => new Tuple<int, int>(s.RobNumStart, s.RobNumEnd));
            robs.AddRange(areas);

            RobsDetVM vm = new RobsDetVM()
            {
                Title = rush.Goods.Title,
                GdSrc = rush.Goods.GetMainImgPath(),
                RushID = rhid,
                Status = rush.Status,
                ByCount = ors.Count() > 0 ? ors.Sum(s => s.Bycount) : 0,
                Robs = robs,
                PerNum = rush.Per_num,
                AllNeed = rush.All_told
            };
            return View("_PartiaRobDet", vm);
        }

        //返回用户头像地址
        [AllowAnonymous]
        public FilePathResult HeadImg(int uid)
        {
            var url = Server.MapUserHead(uid);
            return File(url, "image/jpeg");
        }

        [HttpPost]
        //修改用户信息
        public JsonResult ChangeInfo(PostUserData data)
        {
            //ErroCode: 1:头像图片大小太大
            PostResult result = new PostResult();
            int uid = HttpContext.GetUserID();
            if (ModelState.IsValid && uid > 0)
            {

                var user = db.Member.First(s => s.Uid == uid);
                user.Petname = data.PetName;
                user.Sex = data.Sex;
                result.Isucc = db.SaveChanges() > 0;
                if (data.HeadImg != null && data.HeadImg.ContentLength > 0)
                {
                    //头像大小超过1M
                    if (data.HeadImg.ContentLength > (1024 * 1024))
                    {
                        result.Isucc = false;
                        result.ErrorCode = 1;
                        return Json(result);
                    }
                    string full = Server.MapPath("/Content/Images/headimg/" + "head_" + uid + ".jpg");
                    //将所有图片格式转成jpg格式
                    using (var bitmap = new System.Drawing.Bitmap(data.HeadImg.InputStream))
                    {
                        bitmap.Save(full, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                    result.Isucc = true;
                }
            }
            return Json(result);
        }

        //返回用户基本信息
        public JsonResult Udata()
        {
            var uid = HttpContext.GetUserID();
            var user = users.GetUser(uid);
            if (user == null) return Json("", JsonRequestBehavior.AllowGet);
            var obj = new
            {
                uid = user.Uid,
                petname = user.Petname,
                remsum = user.Acbal,
                headurl = Server.MapUserHead(user.Uid),
                mob = Tools.MobEncrypt(user.Mobile),
                sex = user.Sex,
                email = user.Email
            };
            return Json(obj, JsonRequestBehavior.AllowGet);
        }

        //账单查询数据
        [OutputCache(Duration = 30, Location = System.Web.UI.OutputCacheLocation.Client)]
        public JsonResult BillData(string datearea, int dire = 0, int trad = 0)
        {
            var uid = HttpContext.GetUserID();
            //处理时间区间
            string[] sp = datearea.Split('~');
            var start = Convert.ToDateTime(sp[0]);
            var end = Convert.ToDateTime(sp[1]);
            string sql = $"select * from [dbo].[Bill] where Uid={uid} and CreateTime between '{sp[0]}' and '{sp[1]}'";
            //var res = db.Bill.Where(w => w.Uid == uid && w.CreateTime >= start && w.CreateTime <= end);
            if (dire >= 0) sql += $"\n and Dire={dire}";
            if (trad > 0) sql += $"\n and Channel = {trad}";
            var res = db.Bill.SqlQuery(sql);
            var arr = res.Select(s => new BillItem()
            {
                Date = s.CreateTime.ToString("yyyy年MM月dd日 hh:mm:ss"),
                Dire = s.Dire,
                Way = s.TradChannels.ChanName,
                Id = s.Id,
                Quota = s.Quota,
                Uid = s.Uid
            });
            return Json(arr.ToArray(), JsonRequestBehavior.AllowGet);
        }

        //账单默认数据
        public JsonResult BillDefData()
        {
            var uid = HttpContext.GetUserID();
            int pidx = int.Parse(HttpContext.Request.Params["page"]);
            int psize = int.Parse(HttpContext.Request.Params["limit"]);
            int dcount;
            var res = db.Bill
                .Where(w => w.Uid == uid)
                .OrderByDescending(w => w.CreateTime)
                .QueryPage(pidx, psize, out dcount).ToArray();

            var datas = new
            {
                code = 0,
                msg = "",
                count = dcount,
                data = res.Select(s => new BillItem()
                {
                    Date = s.CreateTime.ToString("yyyy年MM月dd日 hh:mm:ss"),
                    Dire = s.Dire,
                    Way = s.TradChannels.ChanName,
                    Id = s.Id,
                    Quota = s.Quota,
                    Uid = s.Uid
                }).ToArray()
            };
            return Json(datas, JsonRequestBehavior.AllowGet);
        }

        [OutputCache(Duration = 60, Location = System.Web.UI.OutputCacheLocation.Client)]
        //获取用户每年的账单统计数据
        public JsonResult StatisticalYear()
        {
            var uid = HttpContext.GetUserID();

            var res = db.Bill
                .Where(w => w.Uid == uid)
                .GroupBy(g => new { Year = g.CreateTime.Year, Month = g.CreateTime.Month })
                .OrderBy(o => o.Key.Year)
                .ThenBy(o => o.Key.Month)
                .GroupBy(o => o.Key.Year)
                .ToList();

            var datas = new ArrayList();

            foreach (var year in res)
            {
                int idx = 0;
                var mons = year.ToArray();
                bool hasnext = true;
                int[] mds = new int[12];
                for (int i = 1; i <= 12; i++)
                {
                    if (hasnext)
                    {
                        var mon = mons[idx];
                        if (mon.Key.Month == i)
                        {
                            idx++;
                            hasnext = !(idx >= mons.Length);
                            mds[i - 1] = mon.Sum(s => s.Quota);
                            continue;
                        }
                    }
                    mds[i - 1] = 0;
                }
                datas.Add(new { year = year.Key, datas = mds });
            }

            return Json(datas, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult ChangePwd(AlterPwd mod)
        {
            //errorCode约定：
            //1.校验失败
            //2.原始密码错误
            PostResult result = new PostResult();

            if (!ModelState.IsValid)
            {
                result.Isucc = false;
                result.Errors = ModelState.GetErrors();
                result.ErrorCode = 1;
                return Json(result);
            }
            var uid = HttpContext.GetUserID();

            var user = db.Member.First(u => u.Uid == uid);
            if (user.Pwd != mod.OldPwd)
            {
                result.Isucc = false;
                result.ErrorCode = 2;
                return Json(result);
            }
            user.Pwd = mod.NewPwd;
            db.SaveChanges();
            result.Isucc = true;
            return Json(result);
        }

        //获取用户收藏列表
        public JsonResult UserCollects()
        {
            var uid = HttpContext.GetUserID();
            if (uid < 0) return Json("[]");
            var list = db.Member.First(f => f.Uid == uid).UserCollect.Select(s => s.Gid).ToArray();
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult AddCollect(int gid)
        {
            var result = new PostResult();
            var uid = HttpContext.GetUserID();
            result.Isucc = users.AddFavorites(uid, gid);
            return Json(result);
        }

        [HttpPost]
        public JsonResult CancelCollect(int gid)
        {
            var result = new PostResult();
            var uid = HttpContext.GetUserID();
            result.Isucc = users.CancelFavorites(uid, gid);
            return Json(result);
        }
    }

}